import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_course_video_item_widget.dart';
import 'package:flutter_learn_vi/src/page/trainnew/train_line_course_details_controller.dart';
import 'package:get/get.dart';

import '../../bean/bean_train.dart';
import '../../bean/bean_video_course.dart';
import '../../utils/color_utils.dart';
import '../../utils/string_utils.dart';
import '../common/common_loading_dialog.dart';
import '../train/train_tab_details2_student_page.dart';

class TrainLineCourseDetailsPage extends StatefulWidget {
  //培训ID
  final int trainId;

  const TrainLineCourseDetailsPage({
    Key key,
    @required this.trainId,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TrainLineCourseDetailsPageState();
  }
}

class _TrainLineCourseDetailsPageState extends State<TrainLineCourseDetailsPage>
    with TickerProviderStateMixin {
  TrainLineCourseDetailsController _trainV2DetailsController;

  @override
  void initState() {
    super.initState();
    _trainV2DetailsController = Get.put(
      TrainLineCourseDetailsController(widget.trainId),
      tag: "${widget.trainId}",
    );

    Future.delayed(Duration.zero, () async {
      ///获取培训详情
      await _trainV2DetailsController.requestTrainDetails();
      UserTrainStudyEntity userJoinBean =
          _trainV2DetailsController.userJoinTrainBean;
      if (userJoinBean != null) {
        await _trainV2DetailsController.checkFinishTrainRequest();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      body: GetBuilder(
        id: "root",
        tag: "${widget.trainId}",
        builder: (TrainLineCourseDetailsController controller) {
          return buildAnimatedSwitcher(context);
        },
      ),
      appBar: AppBar(
        title: Text("培训详情"),
      ),
    );
  }

  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(

        //动画执行切换时间
        duration: const Duration(milliseconds: 200),
        //动画构建器 构建指定动画类型
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return FadeTransition(child: child, opacity: animation);
        },
        //执行动画的子 Widget
        //只有子 Widget 被切换时才会触发动画
        child: buildMyScoreHisIntegralWidget());
  }

  buildMyScoreHisIntegralWidget() {
    bool _isLoading = _trainV2DetailsController.getIsLoading();
    if (_isLoading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    TrainBean _trainBean = _trainV2DetailsController.trainBean;
    if (_trainBean == null) {
      return Row(
        children: [
          TextButton(
            onPressed: () async {
              _trainV2DetailsController.requestTrainDetails(click: true);
            },
            child: Text("暂无培训详情"),
          ),
        ],
        mainAxisAlignment: MainAxisAlignment.center,
      );
    }
    //是否加入学习
    UserTrainStudyEntity userJoinBean =
        _trainV2DetailsController.userJoinTrainBean;
    Widget joinWidget = SizedBox();
    if (userJoinBean == null) {
      int trainStatus = _trainBean.trainStatus;

      /// 是否启用培训签到 on 开启；off 不开启
      String openSign = _trainBean.openSign;
      //只有进行中的培训可以加入学习
      if (trainStatus == 5) {
        String startStr = "立即加入学习";
        if (openSign == "on") {
          startStr = "签到";
        }
        joinWidget = Row(
          children: [
            SizedBox(
              width: 200,
              child: ElevatedButton(
                onPressed: () async {
                  _trainV2DetailsController.requestJoinTrain();
                },
                style: ButtonStyle(
                  //圆角
                  shape: MaterialStateProperty.all(RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20))),
                ),
                child: Text(startStr),
              ),
            ),
          ],
          mainAxisAlignment: MainAxisAlignment.center,
        );
      }
    }

    String trainLineStr = "";
    String trainLine = _trainBean.trainLine;
    if (trainLine == "offline") {
      trainLineStr = "线下";
    } else {
      trainLineStr = "线上课程学习";
    }

    int trainStatus = _trainBean.trainStatus;

    String statuesStr = "";
    Color textColor = Colors.blueGrey;
    if (trainStatus == 5) {
      textColor = Colors.green;
      statuesStr = "进行中";
    } else if (trainStatus == 6) {
      statuesStr = "已完成";
      textColor = Colors.green;
    } else if (trainStatus == 9) {
      statuesStr = "未开始";
      textColor = Colors.grey;
    } else if (trainStatus == 102) {
      statuesStr = "培训未开始";
      textColor = Colors.grey;
    } else if (trainStatus == 101) {
      statuesStr = "培训已结束";
      textColor = Colors.grey;
    }

    return RefreshIndicator(
      onRefresh: () async {
        await _trainV2DetailsController.requestTrainDetails();
        return true;
      },
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            children: [
              //培训的基本信息
              Container(
                color: Colors.white,
                padding: EdgeInsets.all(8),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        buildLeftTitle("培训名称"),
                        Expanded(
                          child: Text(
                            "${_trainBean.trainName}",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 8,
                    ),
                    Row(
                      children: [
                        buildLeftTitle("培训方式"),
                        Expanded(
                          child: Text(
                            "$trainLineStr",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 8,
                    ),
                    Row(
                      children: [
                        buildLeftTitle("培训状态"),
                        Expanded(
                          child: Text(
                            "$statuesStr",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        )
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          buildLeftTitle("培训时间"),
                          SizedBox(
                            width: 10,
                          ),
                          Expanded(
                            child: Text(
                              "${_trainBean.startStudyTime} ~ ${_trainBean.endStudyTime}",
                              style: TextStyle(
                                fontSize: 13,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    _trainBean.trainRemark.isEmpty
                        ? SizedBox()
                        : Padding(
                            padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                buildLeftTitle("培训简介"),
                                SizedBox(
                                  width: 10,
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onLongPress: () {
                                      if (_trainBean.trainRemark != null &&
                                          _trainBean.trainRemark.length > 50) {
                                        Get.defaultDialog(
                                          radius: 4,
                                          title: "培训简介",
                                          content: Container(
                                            constraints:
                                                BoxConstraints(maxHeight: 600),
                                            child: SingleChildScrollView(
                                              child:
                                                  Text(_trainBean.trainRemark),
                                            ),
                                          ),
                                          confirm: Container(
                                            alignment: Alignment.center,
                                            child: TextButton(
                                              onPressed: () {
                                                Get.back(result: true);
                                              },
                                              child: Text(
                                                "确认",
                                                style: TextStyle(
                                                    color: Colors.blue),
                                              ),
                                            ),
                                            width: 100,
                                          ),
                                        );
                                      }
                                    },
                                    child: Text(
                                      "${_trainBean.trainRemark ?? ""}",
                                      maxLines: 4,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        buildLeftTitle("参与部门"),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(top: 2),
                            child: Wrap(
                              runSpacing: 10,
                              children: buildDepartment(_trainBean),
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
              buildFinishTrainTips(),
              GetBuilder(
                  id: "signOnOffId",
                  tag: "${widget.trainId}",
                  builder: (TrainLineCourseDetailsController controller) {
                    bool signLoading = controller.signLoading;
                    if (signLoading) {
                      return LoadingWidget();
                    }
                    return buildSignResultTips();
                  }),

              buildFinishResultTips(),
              //线上课程信息
              GetBuilder(
                id: "checkFinishId",
                tag: "${widget.trainId}",
                builder: (TrainLineCourseDetailsController controller) {
                  bool checkFinishLoading = controller.checkFinishLoading;
                  if (checkFinishLoading) {
                    return LoadingWidget();
                  }
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        margin: EdgeInsets.only(bottom: 4),
                        child: buildLineCourseListView(_trainBean),
                        color: Colors.white,
                        padding: EdgeInsets.all(8),
                      ),
                      //是否参与培训
                      joinWidget,
                      buildJoinExamControllerButton(),
                    ],
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildLeftTitle(String title) {
    return Container(
      constraints: BoxConstraints(minWidth: 68),
      child: Text("$title"),
    );
  }

  ///参与的部门
  List<Widget> buildDepartment(TrainBean _trainBean) {
    String department = _trainBean.selectDepartment;
    if (StringUtils.isEmpty(department)) {
      return [buildDepartMentCell("全部部门")];
    } else {
      if (department.contains(",")) {
        List<String> list = department.split(",");
        List<Widget> widgetList = [];
        list.forEach((element) {
          widgetList.add(buildDepartMentCell(element));
        });
        return widgetList;
      } else {
        return [buildDepartMentCell("$department")];
      }
    }
  }

  Widget buildDepartMentCell(String title) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(right: 10),
          padding: EdgeInsets.only(left: 6, right: 6, top: 2, bottom: 2),
          decoration: BoxDecoration(
              color: ColorUtils.getRandomColor(),
              borderRadius: BorderRadius.all(Radius.circular(4))),
          child: Text(
            "$title",
            style: TextStyle(color: Colors.white, fontSize: 9),
          ),
        )
      ],
    );
  }

  Widget buildLineCourseListView(TrainBean trainBean) {
    int count = 0;
    if (trainBean.videoCourseEntityList != null) {
      count = trainBean.videoCourseEntityList.length;
    }

    if (count == 0) {
      return Container(
        child: Text("暂无在线课程"),
      );
    }
    UserTrainStudyEntity userJoinTrainBean =
        _trainV2DetailsController.userJoinTrainBean;
    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        CourseAndTeacherBean cubean;
        BeanVideoCourse beanVideoCourse;
        beanVideoCourse = trainBean.videoCourseEntityList[index];
        return TrainTeacherCourseVideoItemWidget(
          beanVideoCourse: beanVideoCourse,
          index: index,
          trainId: trainBean.trainId,
          trainBean: trainBean,
          openSign: trainBean.openSign,
          isScaffold: true,
          userJoinTrainBean: userJoinTrainBean,
          isRequireUserJoin: true,
        );
        // return TrainCourseVideoItemWidget(
        //   videoCourse: beanVideoCourse,
        //   index: index,
        //   trainId: trainBean.trainId,
        // );
      },
    );
  }

  buildFinishResultTips() {
    TrainBean trainBean = _trainV2DetailsController.trainBean;
    UserTrainStudyEntity userJoinTrainBean =
        _trainV2DetailsController.userJoinTrainBean;
    if (trainBean == null) {
      return SizedBox();
    }
    if (userJoinTrainBean == null) {
      return SizedBox();
    }
    String finishStr = trainBean.finishStr;
    if (finishStr == null || finishStr.isEmpty) {
      return SizedBox();
    }
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 8, top: 12, bottom: 12, right: 8),
      margin: EdgeInsets.only(bottom: 8),
      child: Row(
        children: [
          Image.asset(
            "assets/images/3.0x/train_result_icon.png",
            width: 18,
          ),
          SizedBox(
            width: 12,
          ),
          Expanded(child: Text(finishStr)),
        ],
      ),
    );
  }

  ///显示签到签退
  buildSignResultTips() {
    TrainBean trainBean = _trainV2DetailsController.trainBean;
    UserTrainStudyEntity userJoinTrainBean =
        _trainV2DetailsController.userJoinTrainBean;
    if (trainBean == null) {
      return SizedBox();
    }
    if (userJoinTrainBean == null) {
      return SizedBox();
    }
    String startTimeStr = userJoinTrainBean.startTimeStr;
    if (startTimeStr == null || startTimeStr.isEmpty) {
      return SizedBox();
    }
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 8, top: 12, bottom: 12, right: 8),
      margin: EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(
            "assets/images/3.0x/train_sign_icon.png",
            width: 18,
          ),
          SizedBox(
            width: 12,
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("签到时间:$startTimeStr"),
                SizedBox(height: 8),
                buildSignOutWidget(userJoinTrainBean, trainBean),
              ],
            ),
          ),
        ],
      ),
    );
  }

  buildSignOutWidget(
      UserTrainStudyEntity trainStudyEntity, TrainBean trainBean) {
    String signOffTimeStr = trainStudyEntity.signOffTimeStr;
    if (signOffTimeStr == null || signOffTimeStr.isEmpty) {
      /// 是否启用培训签到 on 开启；off 不开启
      String openSign = trainBean.openSign;
      if (openSign == "off") {
        return SizedBox();
      }
      int statues = trainStudyEntity.statues;
      if (statues == 0) {
        return Padding(
          padding: const EdgeInsets.only(top: 10.0),
          child: Text(
            "完成培训后 可签退",
            style: TextStyle(color: Colors.grey),
          ),
        );
      }
      int trainStatus = trainBean.trainStatus;
      if (trainStatus != 5) {
        return Padding(
          padding: const EdgeInsets.only(top: 10.0),
          child: Text(
            "培训已结束 未签退",
            style: TextStyle(color: Colors.grey),
          ),
        );
      }

      return Row(
        children: [
          SizedBox(
            width: 200,
            child: ElevatedButton(
              onPressed: () async {
                _trainV2DetailsController.requestTrainOff();
              },
              style: ButtonStyle(
                //圆角
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20))),
              ),
              child: Text("立即签退"),
            ),
          )
        ],
      );
    }
    return Text("签退时间:$signOffTimeStr");
  }

  buildFinishTrainTips() {
    TrainBean trainBean = _trainV2DetailsController.trainBean;
    UserTrainStudyEntity userJoinTrainBean =
        _trainV2DetailsController.userJoinTrainBean;
    if (trainBean == null) {
      return SizedBox();
    }
    if (userJoinTrainBean == null) {
      return SizedBox();
    }
    int trainStatus = trainBean.trainStatus;
    if (trainStatus != 5) {
      return Row(
        children: [
          Expanded(
              child: Divider(
            color: Colors.red,
            height: 33,
          )),
          Text(
            "培训已结束",
            style: TextStyle(color: Colors.red),
          ),
          Expanded(
              child: Divider(
            color: Colors.red,
            height: 33,
          )),
        ],
      );
    }

    int statues = userJoinTrainBean.statues;
    if (statues == 0) {
      return Row(
        children: [
          Expanded(
              child: Divider(
            color: Colors.red,
            height: 33,
          )),
          Text(
            "当前您还未完成培训课程",
            style: TextStyle(color: Colors.red),
          ),
          Expanded(
              child: Divider(
            color: Colors.red,
            height: 33,
          )),
        ],
      );
    }
    return Row(
      children: [
        Expanded(
            child: Divider(
          color: Colors.green,
          height: 33,
        )),
        Text(
          "当前您已完成培训课程",
          style: TextStyle(color: Colors.green),
        ),
        Expanded(
            child: Divider(
          color: Colors.green,
          height: 33,
        )),
      ],
    );
  }

  ///参加考试按钮
  buildJoinExamControllerButton() {
    TrainBean trainBean = _trainV2DetailsController.trainBean;
    UserTrainStudyEntity userJoinTrainBean =
        _trainV2DetailsController.userJoinTrainBean;
    if (trainBean == null) {
      return SizedBox();
    }
    if (trainBean.showTrainExam == 0) {
      return SizedBox();
    }
    if (userJoinTrainBean == null) {
      return SizedBox();
    }
    int statues = userJoinTrainBean.statues;
    if (statues == 0) {
      return Text("完成培训后 可参与考试 ");
    }
    return ElevatedButton(
      onPressed: () async {
        TrainApproveBean approveBean = TrainApproveBean(
            trainBean.trainId, trainBean.commitTime,
            examId: trainBean.examId);
        await Get.to(() => TrainTabDetails2StudentPage(
              trainBean: trainBean,
              approveBean: approveBean,
            ));
      },
      child: Text("查看考试"),
    );
  }
}
